package csu.web.credit_bank.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import csu.web.credit_bank.mapper.IdPoolMapper;
import csu.web.credit_bank.pojo.IdPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UUIDManager {
    @Autowired
    private IdPoolMapper idPoolMapper;


    public void generateUUID() {
        // 生成UUID

        String uuid = java.util.UUID.randomUUID().toString();
        // 将UUID插入到ID池中
        IdPool idPool = new IdPool();
        idPool.setId(uuid);
        idPoolMapper.insert(idPool);
    }
    //获取一个uuid
    public String getUUID() {
        // 从ID池中获取一个UUID
       IdPool idPool = idPoolMapper.selectOne(new QueryWrapper<IdPool>()
               .orderByAsc("id") // Sort records by ID in ascending order
               .last("LIMIT 1")); // Limit the result to one record
       if (idPool != null) {
           idPoolMapper.delete(new QueryWrapper<IdPool>().eq("id", idPool.getId()));
           return idPool.getId();
       }
        return null;
    }
    public void generateUUID(int num) {
        for (int i = 0; i < num; i++) {
            generateUUID();
        }
    }

}
